package com.jckl.foodathon.dao;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.jckl.foodathon.model.Brand;

public class BrandDAO {
	
	public boolean newBrand(Brand brand){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		boolean createdSuccess = false;
		
		try{
			pm.makePersistent(brand);
			createdSuccess = true;
		}finally{
			pm.close();
		}
		return createdSuccess;
	}
	
	public List<Brand> getBrandsByLatest(){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(Brand.class);
		
		List<Brand> brands = new ArrayList<Brand>();

		try{
			query.setOrdering("updatedDate desc");
			brands = (List<Brand>) query.execute();
			
		}finally{
			pm.close();
			query.closeAll();
		}
		return brands;
	}
	
	public List<Brand> getBrands(){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(Brand.class);
		
		List<Brand> brands = new ArrayList<Brand>();

		try{
			query.setOrdering("name asc");
			brands = (List<Brand>) query.execute();
			
		}finally{
			pm.close();
			query.closeAll();
		}
		return brands;
	}
	
	public Brand getBrandByName(String brandName){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(Brand.class);
		
		List<Brand> brands = null;
		Brand brand = null;

		try{
			query.setFilter("name == brandName");
			query.declareParameters("String brandName");
			brands = (List<Brand>) query.execute(brandName);
			
			if(brands.size()>0){
				brand = brands.get(0);
			}
		}catch (Exception ex){
			ex.printStackTrace();
		}finally{
			pm.close();
			query.closeAll();
		}
		return brand;
	}
	
	public boolean updateBrand (Brand brand){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		boolean updatedSuccess = false;
		
		try{
			pm.makePersistent(brand);
			updatedSuccess = true;
		}finally{
			pm.close();
		}
		return updatedSuccess;
	}
	
}
